<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\manystore\model\Spec as SpecModel;
use app\manystore\model\Specvalue as SpecValueModel;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Integralgoods extends Backend
{
    private $SpecModel;
    private $SpecValueModel;

    /**
     * Goods模型对象
     * @var \app\manystore\model\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->SpecModel = new SpecModel;
        $this->SpecValueModel = new SpecValueModel;
        $this->model = new \app\manystore\model\Goods;
        $this->view->assign("specTypeList", $this->model->getSpecTypeList());
        $this->view->assign("deductStockTypeList", $this->model->getDeductStockTypeList());
        $this->view->assign("goodsStatusList", $this->model->getGoodsStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $not_where = ['goods.parent_id'];
            list($where, $sort, $order, $offset, $limit,$page, $alias, $bind,$self_processing) = $this->buildparams(null,null,$not_where);

            $where_buf = [];
            if ( $self_processing ) {
                if ( isset($self_processing['goods.parent_id']) ) {
                    $c_ids =  db('goods_category')->where(['parent_id'=>$self_processing['goods.parent_id'][2]])->column('id');
                    $where_buf['goods.cat_id'] = ['in',$c_ids];
                }
            }
            $list = $this->model
                    ->with(['goodscategory','shopgoodscategory','manystoreshop'])
                    ->where($where_buf)
                    ->where($where)
                    ->where(['goods.type'=>'2'])
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $min_price = db('goods_spec')->where(['goods_id'=>$row->goods_id])->order('goods_price asc')->find();
                $row->integral = isset($min_price['integral'])?$min_price['integral']:0;
                $row->stock_num = isset($min_price['stock_num'])?$min_price['stock_num']:0;
                $row->getRelation('goodscategory')->visible(['name']);
				$row->getRelation('shopgoodscategory')->visible(['name']);
                $row->getRelation('manystoreshop')->visible(['name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig("updategoods", $this->auth->check("integralgoods/updategoods"));
        $this->assignconfig("goods_edit", $this->auth->check("integralgoods/edit"));
        return $this->view->fetch();
    }

    /*
    *选择商城商品分類
     */
    public function select($value='')
    {
        $parent_id = $this->request->get('parent_id');
        $where = ['deletetime'=>null,'type'=>'2'];
        if ( $parent_id ) {
            $where['parent_id'] = $parent_id;
        }

        $list = db('goods_category')->field('id as value, name')->where($where)->order('weigh desc,id desc')->select();
        $this->success('', null, $list);
    }

    public function addSpec($spec_name, $spec_value,$goods_id=0){
         // 判断规格组是否存在
        if (!$specId = $this->SpecModel->getSpecIdByName($spec_name,$goods_id)) {
            // 新增规格组and规则值
            if ($this->SpecModel->add($spec_name,$goods_id)
                && $this->SpecValueModel->add($this->SpecModel['id'], $spec_value))
                return $this->success('', '', [
                    'spec_id' => (int)$this->SpecModel['id'],
                    'spec_value_id' => (int)$this->SpecValueModel['id'],
                ]);
            return $this->error();
        }
        //return ;
        // 判断规格值是否存在
        if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($specId, $spec_value)) {
            return $this->success('', '', [
                'spec_id' => (int)$specId,
                'spec_value_id' => (int)$specValueId,
            ]);
        }
        // 添加规则值
        if ($this->SpecValueModel->add($specId, $spec_value))
            return $this->success('', '', [
                'spec_id' => (int)$specId,
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
        return $this->error();
    }


    /**
     * 添加规格值
     */
    public function addSpecValue($spec_id, $spec_value)
    {
        // 判断规格值是否存在
        if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($spec_id, $spec_value)) {
            return $this->success('', '', [
                'spec_value_id' => (int)$specValueId,
            ]);
        }
        // 添加规则值
        if ($this->SpecValueModel->add($spec_id, $spec_value))
            return $this->success('', '', [
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
        return $this->error();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $spec_many_params = $this->request->post("spec_many/a");
            $spec_params = $this->request->post("spec/a");
            if ($params) {
                $params['type'] = '2';
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if ( !$spec_params['integral'] ) {
                    $this->error('請輸入積分,積分不能為零');
                }
                if ( !$spec_params['stock_num'] ) {
                    $this->error('請輸入庫存,庫存不能為零');
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['shop_id'] = SHOP_ID;
                    $params['cat_id'] = input('cat_id',0);
                    $result = $this->model->allowField(true)->save($params);
                    //\think\Log::write('hawk-1 result'.json_encode($result), \think\Log::NOTICE);
                    if ($result !== false) {
                        //成功之后 存储商品规格
                        //\think\Log::write('hawk0 spec_many_params'.json_encode($spec_many_params), \think\Log::NOTICE);
                        $this->model->addGoodsSpec($params,$spec_many_params,$spec_params);
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * 上架下架
     */
    public function updategoods($ids = "")
    {
        $action = input('action','ordinary');
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $title = '';
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['goods_status'] == '10') {
                        $where = ['goods_status'=>'20'];
                    }else{
                        $where = ['goods_status'=>'10'];;
                    }
                    if ( $action == 'select' ) {
                        $where = ['goods_status'=>'20'];
                    }
                    $count += $v->save($where);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ( $action == 'select' ) {
                $this->success();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('操作失败'));
            }
        }
        $this->error(__('操作失败', 'ids'));
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if($this->shopIdAutoCondition){
            $this->model->where(array('shop_id'=>SHOP_ID));
        }
        // $row = $this->model->where(array('id'=>$ids))->find();
        $row = $this->model->get($ids, ['specRel', 'spec', 'spec_rel.spec']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $category = db('goods_category')->field('id as value,parent_id, name')->where(['id'=>$row['cat_id'],'type'=>'2'])->find();
        $f_category = db('goods_category')->field('id as value, name')->where(['id'=>$category['parent_id'],'type'=>'2'])->find();
        $this->view->assign("f_category", $f_category);
        $this->view->assign("category", $category);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $spec_params = $this->request->post("spec/a");
            $spec_many_params = $this->request->post("spec_many/a");
            if ($params) {
                if ( !$spec_params['integral'] ) {
                    $this->error('請輸入積分,積分不能為零');
                }
                if ( !$spec_params['stock_num'] ) {
                    $this->error('請輸入庫存,庫存不能為零');
                }
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['shop_id'] = SHOP_ID;
                    $params['cat_id'] = input('cat_id',0);
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        //成功之后 存储商品规格
                        $row->addGoodsSpec($params,$spec_many_params,$spec_params, true);
                    } else {
                        Db::rollback();
                        $this->error($row->getError());
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 多规格信息
        $specData = 'null';
        if ($row['spec_type'] === '20'){
            $specData = json_encode($this->model->getManySpecData($row['spec_rel'], $row['spec']));
        }
        $row['specData'] = $specData;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
